package com.wit.witmg.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wit.witmg.constants.SysConstants;
import com.wit.witmg.entity.TEDdata;
import com.wit.witmg.entity.TEDdata;
import com.wit.witmg.entity.TTjdzpcom;
import com.wit.witmg.mapper.TEDdataMapper;
import com.wit.witmg.mapper.TTjdzpcomMapper;
import com.wit.witmg.service.ITEDdataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wit.witmg.service.ITTjdzpcomService;
import com.wit.witmg.util.DateUtil;
import com.wit.witmg.util.ErrorCode;
import com.wit.witmg.util.JsonResult;
import com.wit.witmg.util.StringUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author bob
 * @since 2025-03-25
 */
@Service
@RequiredArgsConstructor
public class TEDdataServiceImpl extends ServiceImpl<TEDdataMapper, TEDdata> implements ITEDdataService {
    final TTjdzpcomMapper tjMapper;
    @Override
    @Transactional(rollbackFor = {java.lang.Exception.class})
    public Object add(HttpServletRequest request,String sn, String json) {
        if(sn!=null && !sn.equals(SysConstants.SN)){
            return JsonResult.error(ErrorCode.ERR_406);
        }
        List<TEDdata> list= JSONObject.parseArray(json, TEDdata.class);
        if(list!=null){
            boolean bl= saveBatch(list);
            if(bl){
                return JsonResult.success("上传成功");
            }
        }
        return JsonResult.error(ErrorCode.ERR_504);
    }

    @Override
    public Object get(HttpServletRequest request, String ph,String xh,boolean bl) {
        QueryWrapper<TEDdata> qw=new QueryWrapper<>();
        qw.eq("PiHao",ph);
        if(ph!=null && xh!=null){
            qw.eq("XuHao",xh);
            qw.last("limit 1");
            return JsonResult.success(getOne(qw));
        }
        if(ph!=null) {//批号查询返回值包括：第一条时间、最后一条的时间，样品数，合格率，试验结果的平均值，总体标准差。
            List<TEDdata> list = list(qw);
            if (!bl) {
                return JsonResult.success(list);
            }

            //添加到统计表
            // 获取第一条时间
            QueryWrapper<TEDdata> firstTimeQw = new QueryWrapper<>();
            firstTimeQw.eq("PiHao", ph);
            firstTimeQw.orderByAsc("RiQi").last("limit 1");
            TEDdata firstRecord = getOne(firstTimeQw);
            String firstTime = firstRecord != null ? firstRecord.getRiQi() : null;

            // 获取最后一条时间
            QueryWrapper<TEDdata> lastTimeQw = new QueryWrapper<>();
            lastTimeQw.eq("PiHao", ph);
            lastTimeQw.orderByDesc("RiQi").last("limit 1");
            TEDdata lastRecord = getOne(lastTimeQw);
            String lastTime = lastRecord != null ? lastRecord.getRiQi() : null;

            // 获取样品数
            QueryWrapper<TEDdata> countQw = new QueryWrapper<>();
            countQw.eq("PiHao", ph);
            int sampleCount = count(countQw);

            // 获取合格数
            QueryWrapper<TEDdata> qualifiedCountQw = new QueryWrapper<>();
            qualifiedCountQw.eq("PiHao", ph);
            qualifiedCountQw.eq("ResultClass", "1");
            int qualifiedCount = count(qualifiedCountQw);
//            double qualificationRate = sampleCount > 0 ? (double) qualifiedCount / sampleCount : 0;

            // 获取试验结果的平均值和总体标准差
            QueryWrapper<TEDdata> avgU1mAQw = new QueryWrapper<>();
            avgU1mAQw.eq("PiHao", ph);
            avgU1mAQw.ne("U1mA", "no data");
            avgU1mAQw.select("AVG(U1mA) as avgU1mA", "STDDEV_POP(U1mA) as stdU1mA"); // 假设试验结果字段为 "U1mA"
            List<Map<String, Object>> avgU1mAList = listMaps(avgU1mAQw);
            double avgU1mA = avgU1mAList.isEmpty() ? 0 : (double) avgU1mAList.get(0).get("avgU1mA");
            double stdU1mA = avgU1mAList.isEmpty() ? 0 : (double) avgU1mAList.get(0).get("stdU1mA");

            QueryWrapper<TEDdata> avgIlQw = new QueryWrapper<>();
            avgIlQw.eq("PiHao", ph);
            avgIlQw.ne("Il", "no data");
            avgIlQw.select("AVG(Il) as avgIl", "STDDEV_POP(Il) as stdIl");
            List<Map<String, Object>> avgIlList = listMaps(avgIlQw);
            double avgIl = avgIlList.isEmpty() ? 0 : (double) avgIlList.get(0).get("avgIl");
            double stdIl = avgIlList.isEmpty() ? 0 : (double) avgIlList.get(0).get("stdIl");

            // 构建返回结果
//                JSONObject result = StringUtils.instance.getBaseResultObj();
//                result.put("time0", firstTime);
//                result.put("time1", lastTime);
//                result.put("qt", sampleCount);
//                result.put("qqt", qualifiedCount);
//                result.put("avgU1mA", avgU1mA);
//                result.put("stdU1mA", stdU1mA);
//                result.put("avgIl", avgIl);
//                result.put("stdIl", stdIl);
//                result.put("ph", ph);

            TTjdzpcom ent = new TTjdzpcom();
            ent.setPh(ph);
            ent.setTp("14");
            ent.setDt0(DateUtil.getDateFromString(firstTime));
            ent.setDt1(DateUtil.getDateFromString(lastTime));
            ent.setQqt((double) qualifiedCount);
            ent.setQt((double) sampleCount);
            ent.setV0(avgU1mA);
            ent.setV1(avgIl);
            ent.setS0(stdU1mA);
            ent.setS1(stdIl);
            tjMapper.insert(ent);
            return JsonResult.success(ent);


        }
        return JsonResult.error(ErrorCode.ERR_200);
    }
}
